package com.alcatel_lucent.osp;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;
import java.util.ResourceBundle;

import com.alcatel_lucent.osp.action.UserContext;

/**
 * Author: Allan YANG Date: 2008-11-13
 */
@SuppressWarnings("serial")
public class BusinessException extends RuntimeException {
    // general
    static public final int ACCESS_DENIED = 100;

    public static final int LDAP_CONNECTION_ERROR = 1001;


    private int errorCode;
    private String errorMessage;
    private Object[] parameters;
    private Collection<BusinessException> nested;


    public BusinessException(int errorCode, Object... params) {
        this.errorCode = errorCode;
        this.parameters = params;
    }

    public BusinessException(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public Object[] getParameters() {
        return parameters;
    }

    public void setParameters(Object[] parameters) {
        this.parameters = parameters;
    }

    public void addNestedException(BusinessException exception) {
        if (nested == null) {
            nested = new ArrayList<BusinessException>();
        }
        nested.add(exception);
    }

    public boolean hasNestedException() {
        return nested != null && !nested.isEmpty();
    }

    /**
     * Get error message in specified locale.
     *
     * @param locale locale
     * @return error message
     */
    public String toString(Locale locale) {
        StringBuffer result = new StringBuffer();
        if (null != errorMessage) {
            result.append(errorMessage);
        } else {
            ResourceBundle bundle = ResourceBundle.getBundle("errors", locale);
            String localizedString = bundle.getString("business_exception_"
                    + errorCode);
            MessageFormat msgFmt = new MessageFormat(localizedString, locale);
            result.append(msgFmt.format(parameters));
        }
        if (nested != null) {
            for (BusinessException ne : nested) {
                result.append("\n").append(ne.toString(locale));
            }
        }
        return result.toString();
    }

    /**
     * Display error message including nested exceptions.
     */
    public String toString() {
        UserContext context = UserContext.getInstance();
        Locale locale = null != context ? context.getLocale() : Locale.getDefault();
        return toString(locale);
    }

    public Collection<BusinessException> getNested() {
        return nested;
    }

    public void setNested(Collection<BusinessException> nested) {
        this.nested = nested;
    }
    
    @Override
    public String getMessage() {
    	return toString();
    }
}
